#!/usr/bin/env python
#-*-coding:utf-8-*-
'练车系统爬虫测试'
from  urllib  import  request,parse
from  http import  cookiejar
import  json
import  re
from  time import sleep
import sys
import os
cnt=1
m=70 #尝试次数
flag=False
global null
null = None
global false
false = False
global true
true = True
user=''
passwd=''
day=''
start=0
endl=0
ur='练车.log'
'''无意义，转化字典必备'''
if __name__=='__main__':
    l=sys.argv
    if(len(l)==7):
        user=l[1];
        passwd=l[2];
        day=l[3];
        start=int(l[4]);
        endl=int(l[5]);
        ur=l[6]
    else:
        user = input('请输入用户名')
        passwd = input('请输入密码')
        day = input('请输入日期 yyyy-mm-dd 例如 2018-05-15')  # 手动改,暂时没实现获得时间
        start = int(input('请输入最早开始时间'))  # 开始时间最早2
        endl = int(input('请输入最晚开始时间'))  # 最晚

f=open(ur,'ab+')
#sleep(8)
while(cnt<m):
    try:
        '''登录模块'''
        head = {}
        url = 'http://yykfyljx.ay001.net/Server/AccountServer.asmx/MobileLogin'
        head['Content-Type'] = 'application/json';
        head['User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0'
        cookie = cookiejar.CookieJar()

        pere = request.HTTPCookieProcessor(cookie)
        opnner = request.build_opener(pere);
        try:
            opnner.open(request.Request(url='http://yykfyljx.ay001.net/Account/AppType', headers=head))
        except:
            print('网页无法打开.....脚本已经失效')
            f.write('网页无法打开.....脚本已经失效\n'.encode('uft-8'))
            
            break
        date = {"UserName": user, "Password": passwd, "LoginType": 0}
        data = json.JSONEncoder().encode(date).encode('utf-8')
        s = ""
        for i in cookie:
            s = i.value
        head['Cookie'] = 'ASP.NET_SessionId=' + s

        login_rep = request.Request(headers=head, data=data, url=url);
        try:
            login_res = request.urlopen(login_rep)
        except:
            print('页面无法打开,登录失败！！')
            f.write('页面无法打开,登录失败！！\n'.encode('utf-8'))
            
            break
        # print(login_res.read())
        s=eval(login_res.read().decode('utf-8'))
        #print(s['d']) #登录返回值
       # break
        if s['d']['isSuccess']:
            print('登陆成功！！')
            f.write('登陆成功\n'.encode('utf-8'))
        else:
            print(s['d']['Message'])
            f.write((s['d']['Message']+'\n').encode('utf-8'))
            break

        '''获得信息'''
        '''注释为获得的个人信息,对于选车无用'''
        #date = {}
        #data = json.JSONEncoder().encode(date).encode('utf-8')
        head['Cookie'] = head['Cookie'] + ';rmbUser=false; username=; password='
        #imf_rep = request.Request(url='http://yykfyljx.ay001.net/Server/BaseInfoServer.asmx/GetUserInfo', headers=head,data=data)
        #imf_res = request.urlopen(imf_rep)
        #qs = imf_res.read()
        # print(str(qs,encoding='utf-8')) #d登录返回信息

        '''获取教练'''

        date = {"argDay": "2018-5-11", "nUnitNO": 3, "nPageIndex": 1}
        data = json.JSONEncoder().encode(date).encode('utf-8')
        teacher_rep = request.Request(url='http://yykfyljx.ay001.net/Server/OrderCoachServer.asmx/GetInfoByTimeId', headers=head, data=data)
        try:
            teacher_res = request.urlopen(teacher_rep)
        except:
            print('无法获得教练信息,你可能还没有选教练..')
            f.write('无法获得教练信息,你可能还没有选教练..\n'.encode('utf-8'))
            break
        teacher = teacher_res.read();
        dic = eval(teacher.decode('utf-8'))
        # print(dic)  #教练信息
        '''
            for (u,v) in dic['d'].items():
            print(u,"  ",v)
        '''
        teacher_data = eval(dic['d']['Data'])
        teacher_data = teacher_data['BusinessData']['教练信息']['Data'][0]
        print('教练编号:', teacher_data['教练__编号'], '姓名:', teacher_data['教练__姓名'], '满意度:', teacher_data['教练__满度'], '手机:',
              teacher_data['教练__手机'], '车号:', teacher_data['教练__车辆信息__车牌号'])

        '''获取日期练车安排'''
        head['HidIsCard'] = 'false'
        date = {"coachID": teacher_data['教练__编号'], "date": day, "subid": 0}
        data = json.JSONEncoder().encode(date).encode('utf-8')
        margement = request.Request(url='http://yykfyljx.ay001.net/Server/OrderCoachServer.asmx/GetTimesInfoByCoachIDNew', headers=head, data=data)
        information = request.urlopen(margement).read()
        dicc = eval(information.decode('utf-8'))
        dicc = eval(dicc['d'])
        '''
            for (u,v) in dicc.items():
            print(u,'.....',v,type(v))
        '''
        # print(dicc['Data'][0],type(dicc['Data'][0]))
        for di in dicc['Data']:
            print(di)
        list = []
        for i, di in enumerate(dicc['Data']):
            if (di['状态'] == '可用'):
                list.append(i)
        for i in list:
            print(dicc['Data'][i]['培训日期'][:10], ' ', dicc['Data'][i]['编号'], '  ', dicc['Data'][i]['开始时间'], '----',dicc['Data'][i]['结束时间'], '未满')
            f.write((dicc['Data'][i]['培训日期'][:10]+' '+str(dicc['Data'][i]['编号'])+'  '+dicc['Data'][i]['开始时间']+'----'+dicc['Data'][i]['结束时间']+'未满\n').encode('utf-8'))

        '''塞选模块 '''

        print(list)
        t_list = []
        for i in list:
            if (int(dicc['Data'][i]['开始时间'][0:2]) >= start and int(dicc['Data'][i]['开始时间'][0:2]) <= endl and int(dicc['Data'][i]['开始时间'][0:2])!=11):
                t_list.append(i)
        list = None
        print(t_list)
        print(len(t_list))
        if(len(t_list)==0):
            print('没有可选时间')
            f.write('没有可选时间\n'.encode('utf-8'))
            break
        '''预约模块'''
        #t_list=[]
        #t_list.append(5)
        date = {'PXResID': '', "SubID": dicc['Data'][t_list[0]]['科目__编号'], 'stateID': dicc['Data'][t_list[0]]['编号']}
        data = json.JSONEncoder().encode(date).encode('utf-8')
        y_res = request.Request(data=data, url='http://yykfyljx.ay001.net/Server/OrderCoachServer.asmx/orderCoachNew',headers=head)
        try:
            y_rep = request.urlopen(y_res)
        except:
            print('练车预约模块错误,无法预约')
            f.write('练车预约模块错误,无法预约\n'.encode('utf-8'))
            break
        s = y_rep.read().decode('utf-8')
        print(s)
        s=eval(s)
        if(s['d']['Item1']):
            flag=True
            break
        else:
            print(s['d']['Item2'][0])
            f.write(s['d']['Item2'][0].encode('utf-8'))
            sleep(10)
            cnt+=10
            #break
    except:

        sleep(1)
        print('错误,正在第'+str(cnt)+'尝试')
	
        cnt+=10

if not flag:
    print('预约失败')
    f.write('预约失败\n'.encode('utf-8'))
else:
    print('预约成功, 时间为 ',day,dicc['Data'][t_list[0]]['开始时间'],'----',dicc['Data'][t_list[0]]['结束时间'])
    f.write(('预约成功, 时间为 '+day+dicc['Data'][t_list[0]]['开始时间']+'----'+dicc['Data'][t_list[0]]['结束时间']+'\n').encode('utf-8'))
    print('欢迎再次使用!!')

f.write('\n'.encode('utf-8'))
f.close()














